package com.jzo2o.customer.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.model.CurrentUser;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.UserContext;
import com.jzo2o.customer.enums.AuditStatusEnum;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.AgencyAuditMapper;
import com.jzo2o.customer.mapper.AgencyCertificationMapper;
import com.jzo2o.customer.model.domain.AgencyAudit;
import com.jzo2o.customer.model.domain.AgencyCertification;
import com.jzo2o.customer.model.dto.AgencyCertificationUpdateDTO;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.CertificationAuditReqDTO;
import com.jzo2o.customer.model.dto.response.AgencyCertificationAuditResDTO;
import com.jzo2o.customer.model.dto.response.RejectReasonResDTO;
import com.jzo2o.customer.service.IAgencyCertificationService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 机构认证信息表 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-06
 */
@Service
public class AgencyCertificationServiceImpl extends ServiceImpl<AgencyCertificationMapper, AgencyCertification> implements IAgencyCertificationService {

    @Resource
    private AgencyCertificationMapper agencyCertificationMapper;
    @Resource
    private AgencyAuditMapper agencyAuditMapper;


    /**
     * 根据机构id更新
     *
     * @param agencyCertificationUpdateDTO 机构认证更新模型
     */
    @Override
    public void updateByServeProviderId(AgencyCertificationUpdateDTO agencyCertificationUpdateDTO) {
        LambdaUpdateWrapper<AgencyCertification> updateWrapper = Wrappers.<AgencyCertification>lambdaUpdate()
                .eq(AgencyCertification::getId, agencyCertificationUpdateDTO.getId())
                .set(AgencyCertification::getCertificationStatus, agencyCertificationUpdateDTO.getCertificationStatus())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getName()), AgencyCertification::getName, agencyCertificationUpdateDTO.getName())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getIdNumber()), AgencyCertification::getIdNumber, agencyCertificationUpdateDTO.getIdNumber())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getLegalPersonName()), AgencyCertification::getLegalPersonName, agencyCertificationUpdateDTO.getLegalPersonName())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getLegalPersonIdCardNo()), AgencyCertification::getLegalPersonIdCardNo, agencyCertificationUpdateDTO.getLegalPersonIdCardNo())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getBusinessLicense()), AgencyCertification::getBusinessLicense, agencyCertificationUpdateDTO.getBusinessLicense())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getCertificationTime()), AgencyCertification::getCertificationTime, agencyCertificationUpdateDTO.getCertificationTime());
        super.update(updateWrapper);
    }

    /**
     * 机构端提交认证申请
     *
     * @param auditAddReqDTO
     * @return
     */
    @Override
    public AgencyCertification submitAuth(AgencyCertificationAuditAddReqDTO auditAddReqDTO) {
        //1、获取服务人员id
        Long workerId = UserContext.currentUserId();

        //2、dto转换为实体
        AgencyCertification agencyCertification = BeanUtils.toBean(auditAddReqDTO, AgencyCertification.class);

        //3、将状态改为认证中、设置id、创建和更新时间
        agencyCertification.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        agencyCertification.setId(workerId);
        agencyCertification.setCreateTime(LocalDateTime.now());
        agencyCertification.setUpdateTime(LocalDateTime.now());

        //4、保存
        this.saveOrUpdate(agencyCertification);

        //5、修改agency_audit表信息
        AgencyAudit agencyAudit = new AgencyAudit();
        agencyAudit.setId(workerId);
        agencyAudit.setAuditStatus(AuditStatusEnum.UNAUDITED.getStatus());
        agencyAudit.setUpdateTime(LocalDateTime.now());
        this.agencyAuditMapper.insert(agencyAudit);

        return agencyCertification;
    }

    /**
     * 驳回原因
     *
     * @param certificationAuditReqDTO 认证审核请求模型
     */
    @Override
    public RejectReasonResDTO rejectReason(CertificationAuditReqDTO certificationAuditReqDTO) {
        //创建响应对象
        RejectReasonResDTO rejectReasonResDTO = new RejectReasonResDTO();

        //设置驳回原因
        rejectReasonResDTO.setRejectReason(certificationAuditReqDTO.getRejectReason());
        return rejectReasonResDTO;
    }

    /**
     * 审核机构认证分页查询
     *
     * @param agencyCertificationAuditPageQueryReqDTO
     * @return
     */
    @Override
    public PageResult<AgencyCertificationAuditResDTO> page(AgencyCertificationAuditPageQueryReqDTO agencyCertificationAuditPageQueryReqDTO) {
        PageResult<AgencyCertificationAuditResDTO> pageResult = PageHelperUtils
                .selectPage(agencyCertificationAuditPageQueryReqDTO, () -> agencyCertificationMapper.queryAgencyCertification());
        return pageResult;
    }

    /**
     * 机构认证审核
     *
     * @param id                  机构认证id
     * @param certificationStatus 审核状态
     * @param rejectReason        拒绝原因
     */
    @Override
    public void audit(Long id, Integer certificationStatus, String rejectReason) {
        //1、更新worker_certification表
        LambdaUpdateWrapper<AgencyCertification> updateWrapper = new LambdaUpdateWrapper<AgencyCertification>()
                .set(AgencyCertification::getCertificationStatus, certificationStatus)
                .set(AgencyCertification::getUpdateTime, LocalDateTime.now())
                .eq(AgencyCertification::getId, id);
        //1.1、如果认证状态为：认证成功，则更新认证时间
        if (certificationStatus == CertificationStatusEnum.SUCCESS.getStatus()) {
            updateWrapper.set(AgencyCertification::getCertificationTime, LocalDateTime.now());
        }
        //1.2、更新
        this.update(updateWrapper);

        //2.更新worker_audit表
        //2.1、检查是否已存在该机构的审核记录
        AgencyAudit agencyAudit = agencyAuditMapper.selectById(id);
        //2.2、如果不存在，则创建一条新的审核记录
        if (agencyAudit == null) {
            agencyAudit = new AgencyAudit();
            agencyAudit.setId(id);
            agencyAuditMapper.insert(agencyAudit);
        }
        //2.3、如果存在，则更新现有记录
        agencyAudit.setAuditStatus(AuditStatusEnum.AUDITED.getStatus());
        agencyAudit.setRejectReason(rejectReason);
        agencyAudit.setAuditTime(LocalDateTime.now());
        agencyAudit.setUpdateTime(LocalDateTime.now());
        agencyAudit.setAuditorId(UserContext.currentUserId());
        agencyAudit.setAuditorName(UserContext.currentUser().getName());

        //3、更新
        agencyAuditMapper.updateById(agencyAudit);
    }
}
